#include "stdafx.h"
#include "RSSTREAM.h"

RSSTREAM::RSSTREAM()
{
	m_maxSpeed=0;
	memset(m_speed,0,4*4);

	/*m_timerExit=false;
	m_hTimerThread=NULL;*/

	InitializeCriticalSection(&m_cs);
	/*CreateTimerThread();*/
}

RSSTREAM::~RSSTREAM()
{
	/*ExitTimerThread();*/
	DeleteCriticalSection(&m_cs);
}

void RSSTREAM::AddStream(UINT bytes)
{
	EnterCriticalSection(&m_cs);
	m_speed[3]+=bytes;
	LeaveCriticalSection(&m_cs);
}

UINT RSSTREAM::FlushSpeed()
{
	UINT result;

	EnterCriticalSection(&m_cs);

	result=(m_speed[0]+m_speed[1]+m_speed[2]+m_speed[3])/4;

	m_speed[0]=m_speed[1];
	m_speed[1]=m_speed[2];
	m_speed[2]=m_speed[3];
	m_speed[3]=0;

	static int count=0;

	if(count++>=60)
	{
		m_maxSpeed=0;
		count=0;
	}

	if(result>m_maxSpeed)
		m_maxSpeed=result;

	LeaveCriticalSection(&m_cs);

	return result;
}

UINT RSSTREAM::GetSpeed()
{
	UINT result;

	EnterCriticalSection(&m_cs);

	result=(m_speed[0]+m_speed[1]+m_speed[2]+m_speed[3])/4;
	
	LeaveCriticalSection(&m_cs);

	return result;
}

UINT RSSTREAM::GetMaxSpeed()
{
	UINT result;

	EnterCriticalSection(&m_cs);
	result=m_maxSpeed;
	LeaveCriticalSection(&m_cs);

	return result;
}

//void RSSTREAM::CreateTimerThread()
//{
//	if(NULL==m_hTimerThread)
//	{
//		m_timerExit=false;
//		m_hTimerThread=CreateThread(NULL,0,TimerThread,this,0,NULL);
//	}
//}
//
//void RSSTREAM::ExitTimerThread()
//{
//	if(m_hTimerThread!=NULL)
//	{
//		m_timerExit=true;
//		WaitForSingleObject(m_hTimerThread,INFINITE);
//	}
//}

//DWORD WINAPI RSSTREAM::TimerThread(PVOID pvoid)
//{
//	RSSTREAM *pThis=(RSSTREAM *)pvoid;
//	int count=0;
//
//	while(!pThis->m_timerExit)
//	{
//		Sleep(1500);
//
//		EnterCriticalSection(&pThis->m_cs);
//
//		if(count++>=40)
//		{
//			pThis->m_maxSpeed=0;
//			count=0;
//		}
//	
//		pThis->m_speed=0;
//
//		if(pThis->m_speed>pThis->m_maxSpeed)
//			pThis->m_maxSpeed=pThis->m_speed;
//
//		LeaveCriticalSection(&pThis->m_cs);
//	}
//
//	if(pThis->m_hTimerThread!=NULL)
//	{
//		CloseHandle(pThis->m_hTimerThread);
//		pThis->m_hTimerThread=NULL;
//	}
//
//	return 0;
//}
